# -*-coding: Utf-8 -*-
# @File : db_handler .py
# author: Chimengmeng
# blog_url : https://www.cnblogs.com/dream-ze/
# Time：2024/5/7

from lib import Tools
from conf import settings
import os
import pickle
from typing import Any, Tuple, Optional, Union, List


class Handler:
    def __init__(self):
        self.tools = Tools()

    def __get_file_path(self, obj: Any = None, cls: Any = None) -> Tuple[Any, Any]:
        # 获取到当前对象所在的类的类名
        if not cls and obj:
            cls_name = obj.__class__.__name__
        else:
            cls_name = cls.__name__
        # 拼接当前对象所在的类名对应的文件名
        data_dir = os.path.join(settings.DATA_DIR, cls_name)
        # 确保当前路径存在
        os.makedirs(data_dir, exist_ok=True)
        # 当前文件存在的情况下返回当前文件路径
        if not cls and obj:
            data_path = os.path.join(str(data_dir), str(obj.name))
        else:
            data_path = data_dir
        return data_dir, data_path

    def __get_tag_name(self, cls):
        if cls.__name__ == 'Admin':
            return "管理员"
        elif cls.__name__ == 'School':
            return "学校"
        elif cls.__name__ == 'Student':
            return "学生"
        elif cls.__name__ == 'Teacher':
            return "讲师"
        elif cls.__name__ == 'Course':
            return "课程"

    def read_data(self, cls: type, name: str) -> Tuple[bool, Union[object, None]]:
        try:
            data_dir, data_path = self.__get_file_path(cls=cls)
            data_path = os.path.join(str(data_dir), name)
            with open(file=data_path, mode='rb') as fp:
                data = pickle.load(file=fp)
            return True, data
        except Exception as e:
            return False, None

    def save_data(self, obj: object) -> None:
        '''

        :param obj: 当前对象
        :return:
        '''
        data_dir, data_path = self.__get_file_path(obj=obj)
        with open(file=data_path, mode='wb') as fp:
            pickle.dump(obj=obj, file=fp)

    def read_data_list(self, cls) -> Tuple[bool, List[str]]:
        file_path = os.path.join(settings.DATA_DIR, cls.__name__)
        file_name_list = os.listdir(path=str(file_path))
        return True, file_name_list

    def read_data_dict(self, cls):
        name_dict = {}
        flag, name_list = cls.show_name()
        if not flag:
            return flag, name_list
        print(f"**** 信息如下 ****")
        for index, name in enumerate(name_list, start=1):
            flag, obj = cls.select(name=name)
            index = str(index).rjust(5, '0')
            print(
                f"当前{self.__get_tag_name(cls=cls)}编号 :>>>>  {index} 当前{self.__get_tag_name(cls=cls)}名称 :>>>> {obj.name}")
            name_dict[index] = obj
        return True, name_dict


handler = Handler()


class DBHandler(object):
    # 一个写函数
    def save(self):
        handler.save_data(obj=self)

    # 一个查函数
    @classmethod
    def select(cls, name):
        flag, user_data = handler.read_data(cls=cls, name=name)
        if not flag:
            return flag, user_data
        return flag, user_data

    @classmethod
    def show_name(cls):
        flag, obj_list = handler.read_data_list(cls=cls)
        return flag, obj_list

    @classmethod
    def chose_name(cls):
        flag, name_dict = handler.read_data_dict(cls=cls)
        return flag, name_dict
